<template>
  <div class="user-header">
    <el-button type="primary" @click="addUser">+ 新增</el-button>
    <el-form :model="search" label-width="120px" :inline="true">
      <el-form-item label="请输入">
        <el-input v-model.trim="search.key" @keyup.enter="searchUser" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="searchUser">搜索</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div class="contain">
    <el-table :data="tableData" style="width: 100%" height="auto">
      <el-table-column type="index" width="50"></el-table-column>
      <el-table-column align="center" :show-overflow-tooltip="true" v-for="item in tableLable" :key="item.label"
        :prop="item.prop" :label="item.label" :width="item.width" />
      <el-table-column align="center" fixed="right" label="操作" width="120">
        <template #default="scope">
          <el-button size="small" @click="editUser(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination :page-size="10" :pager-count="11" layout="prev, pager, next" :total="config.total"
      @current-change="clickPage" />
  </div>
  <div class="dialog">
    <el-dialog v-model="dialogVisible" :title="formData.id ? '编辑' : '新增'" width="40%" :before-close="handleClose">
      <el-form ref="formRef" :model="formData" :inline="true" :rules="rules" status-icon>
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input v-model.trim="formData.name" placeholder="请输入姓名" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input v-model.number="formData.age" placeholder="请输入年龄" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="性别" prop="sex">
              <el-select v-model="formData.sex" placeholder="请选择">
                <el-option label="男" value="1" />
                <el-option label="女" value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="出生日期" required>
              <el-form-item prop="birth">
                <el-date-picker v-model="formData.birth" type="date" label="出生日期" placeholder="请选择"
                  style="width: 125px" />
              </el-form-item>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="地址" prop="addr">
              <el-input v-model.trim="formData.addr" placeholder="请输入地址" style="width:390px" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="formatForm">取消</el-button>
          <el-button type="primary" @click="sumbit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang = 'ts'>
import { onMounted, ref, Ref, reactive, getCurrentInstance } from "vue"
import { FormRules } from 'element-plus'
onMounted(() => {
  getUserDatas(config)
})
let app = getCurrentInstance()
let tableData = ref([])
let tableLable = reactive([
  {
    prop: "name",
    label: "姓名",
    width: 100,
  },
  {
    prop: "age",
    label: "年龄",
    width: 100,
  },
  {
    prop: "sex",
    label: "性别",
    width: 100,
  },
  {
    prop: "birth",
    label: "出生日期",
    width: 100,
  },
  {
    prop: "addr",
    label: "地址",
    width: 300,
  },
])
const config: Config = reactive({
  page: 1,
  total: 0,
  name: ''
})
type Config = {
  page: number,
  total: number,
  name: string
}
// 获取数据
const getUserDatas = async (config: Config): Promise<void> => {
  const res = await app?.proxy?.$api.getUserData(config)
  config.total = res.count
  tableData.value = res.list.map((item: any) => {
    item.sex == 0 ? item.sex = '女' : item.sex = '男'
    return item
  })
}

// 分页
const clickPage = (page: number) => {

  config.page = page
  // console.log(config);
  getUserDatas(config)

}
// 搜索
let search: { key: string } = reactive({ key: '' })
const searchUser = (): void => {
  config.name = search.key
  getUserDatas(config)
}

// 新增，编辑
type Form = {
  id: number | string,
  name: string,
  addr: string,
  age: string,
  birth: string,
  sex: number | string
}
let formData: Form = reactive({
  id: '',
  name: '',
  addr: '',
  age: '',
  birth: '',
  sex: ''
})
// 表单校验
const rules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入名字', trigger: 'blur' },
    { min: 2, max: 5, message: '请输入2-5个字符', trigger: 'blur' },
  ],
  sex: [
    { required: true, message: '请选择性别', trigger: 'change' },
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', message: '请输入数字' }
  ],
  addr: [
    { required: true, message: '请输入地址', trigger: 'blur' },
  ],
  birth: [
    { type: 'date', required: true, message: '请选择日期', trigger: 'change' },
  ],
})
let dialogVisible: Ref<boolean> = ref(false)
const handleClose = (): void => {
  formatForm()
}

// 新增
const addUser = (): void => {
  dialogVisible.value = true
  formData.id = ''
}
// 修改
const editUser = (row: any): void => {
  dialogVisible.value = true
  app?.proxy?.$nextTick(() => {
    Object.assign(formData, row)
  })
}
// 删除
const handleDelete = (row: any)=>{
  // console.log(row.id);
  
  ElMessageBox.confirm(
    '是否确定删除这条数据?',
    'Tip',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then( async () => {
      const res = await app?.proxy?.$api.deleteUserData({id:row.id})
      if (res){
        getUserDatas(config)
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      }
    }).catch(() => {

    })
  }
// 提交
const sumbit = () => {
  formData.birth = formatTime(formData.birth)
  // 新增
  if (!formData.id) {
    app?.proxy?.$refs.formRef.validate(async (valid: any) => {
      if (valid) {
        const res = await app?.proxy?.$api.addUserData(formData)
        if (res) {
          formatForm()
          getUserDatas(config)
        }
      } else {
        ElMessage({
          message: '请输入正确内容',
          type: 'error',
        })
      }
    })
  } else {
    // formData.sex = formData.sex == "男" ? (formData.sex = 1) : (formData.sex = 0)
    app?.proxy?.$refs.formRef.validate(async (valid: any) => {
      if (valid) {
        const resd = await app?.proxy?.$api.updateUserData(formData)
        // console.log(res);
        if (resd) {
          app?.proxy?.$refs.formRef.resetFields();
          dialogVisible.value = false
          getUserDatas(config)
        }
      } else {
        ElMessage({
          message: '请输入正确内容',
          type: 'error',
        })
      }
    })
  }
}
// const formRef = ref()
// 退出格式化表单
const formatForm = () => {
  console.log(app?.proxy?.$refs);
  app?.proxy?.$refs.formRef.resetFields();

  dialogVisible.value = false
  // 清除表单数据

}
// 格式化日期
const formatTime = (time: string): string => {
  const formatDate = (dt: any) => {
    dt = dt < 10 ? 0 + dt : dt
    return dt
  }
  const date = new Date(time)
  const year = date.getFullYear()
  let month = date.getMonth() + 1
  month = formatDate(month)
  let day = date.getDate()
  day = formatDate(day)
  return year + '-' + month + '-' + day
}

</script>

<style lang="less" scoped>
.contain {
  padding: 20px;
  // padding-top: 0;
  padding-bottom: 0;
}

.user-header {
  height: 30px;
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
}

// .bir {
//   width: 165px;
// }

// .sex {
//   width: 242.5px;
// }
</style>
